package com.dsteiner.gwt.cafeteriasophia.client.controller;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Map;

import com.dsteiner.gwt.cafeteriasophia.client.event.NavEvent;
import com.dsteiner.gwt.cafeteriasophia.client.model.NavModel;
import com.dsteiner.widgets.client.Widgets.IButton;
import com.dsteiner.widgets.client.Widgets.IHTML;
import com.dsteiner.widgets.client.Widgets.ILazyWidget;
import com.dsteiner.widgets.client.Widgets.IWidget;
import com.dsteiner.widgets.client.Widgets.WidgetListenerAdapter;
import com.dsteiner.widgets.client.event.EventListener;
import com.dsteiner.widgets.client.event.EventManager;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;

public class NavController {

	private NavModel navModel;

	public void registerNavWidget(ILazyWidget navWidget) {
		navWidget.addWidgetListener(new WidgetListenerAdapter() {
			@Override
			public void onAttach(IWidget widget) {
				updateSelectedPage();
			}
		});
	}

	public void registerNavModel(NavModel navModel) {
		this.navModel = navModel;
		navModel.addPropertyChangeListener("selectedPage", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				updateSelectedPage();
			}
		});
	}

	private void updateSelectedPage() {
		int selectedPage = navModel.getSelectedPage();
		Map<Integer, IWidget> pageMap = navModel.getPageMap();
		for (Integer pageId : pageMap.keySet()) {
			IWidget widget = pageMap.get(pageId);
			widget.setVisible(selectedPage == pageId);
		}
	}

	public void registerCreateShiftChangeButton(IButton createShiftChangeButton) {
		createShiftChangeButton.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				navModel.setSelectedPage(NavModel.PAGE_ID_SHIFT_CHANGE);
			}
		});
	}

	public void registerHistoryLink(IHTML historyLink) {
		historyLink.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				navModel.setSelectedPage(NavModel.PAGE_ID_HISTORY);
			}
		});
	}

	public void registerStatisticLink(IHTML statisticLink) {
		statisticLink.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				navModel.setSelectedPage(NavModel.PAGE_ID_STATISTIC);
			}
		});
	}

	public void registerEventManager(EventManager eventManager) {
		eventManager.registerListener(NavEvent.class, new EventListener<NavEvent>() {
			public void onEvent(NavEvent event) {
				navModel.setSelectedPage(event.getPageId());
			}
		});
	}
}